
package com.yuanma.android.boan;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import android.os.AsyncTask;

//import org.apache.http.HttpStatus;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;

public class MessageReadActivity extends MessageActivity {

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_read);
	
	Button readButton = (Button) findViewById(R.id.btnRead);
	if(getMessageFromService().size()==0) readButton.setEnabled(false);

        readButton.setOnClickListener(new View.OnClickListener() {
		public void onClick(View v) {
		    Message msg=JsonPullService.msgsToRead.get(msg_no);
		    String localUrlString=String.format("http://%s:%s/boan/confirmRead.brl?loginName=%s&msg_id=%s",
							Constants.WEB_SERVER_IP,Constants.WEB_SERVER_PORT,
							JsonPullService.loginName,msg.msg_id);
	
		    new ConfirmReadTask().execute(localUrlString);
		
		}
        });

	changeMessage(0);

    }

    private class ConfirmReadTask extends AsyncTask<String, Void, String> {
	
        @Override
	    protected String doInBackground(String... urls) {
	    String result=getString(R.string.http_code_error);
	    
	    try {
		HttpURLConnection localHttpURLConnection = (HttpURLConnection) (new URL(urls[0]).openConnection());
		localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);
		int responseCode = localHttpURLConnection.getResponseCode();
		switch (responseCode) {
		case HttpURLConnection.HTTP_OK:
		    result = Utility.fromStream(localHttpURLConnection.getInputStream());
		    break;
		}
		// Handles possible exceptions
	    } catch (MalformedURLException localMalformedURLException) {

		result= localMalformedURLException.getMessage();

	    } catch (IOException localIOException) {
		result =localIOException.getMessage();
		result =getString(R.string.network_error);
	    } finally {
		
	    }
	    return result;
	    
        }
 
        /**
         * Uses the logging framework to display the output of the fetch
         * operation in the log fragment.
         */
        @Override
	    protected void onPostExecute(String result) {
	    
	    
	    if(result.trim().compareTo("ok")==0){
		Message msg=JsonPullService.msgsToRead.get(msg_no);
		JsonPullService.msgsToReview.add(msg);
		JsonPullService.msgsToRead.remove(msg_no);
		changeMessage(msg_no);
		Button readButton = (Button) findViewById(R.id.btnRead);
		if(getMessageFromService().size()==0) readButton.setEnabled(false);

	    }else{
		TextView hintView = (TextView) findViewById(R.id.read_hint);
		hintView.setText(result);
		
	    }
	    
		
        }
    }
}
